//cookies
import { setToken, setUsername, getUsername, getToken, removeToken, removeUsername } from "@/utils/cookies";
import { login } from "@/api/user"
const state = {
    collapse: JSON.parse(sessionStorage.getItem('collapse')) || false,
    username: "" || getUsername(),
    toolbar: JSON.parse(localStorage.getItem("toolbar") || '{"visible": false, "enter": true}'),
    currentUser: JSON.parse(localStorage.getItem("currentUser") || '{}'),
    webInfo: JSON.parse(localStorage.getItem("webInfo") || '{"webName": "ORDINARY", "webTitle": [], "notices": [], "footer": "", "backgroundImage": "", "avatar": "https://tysz.oss-cn-shanghai.aliyuncs.com/box/img/other/Rjk0dUcn9O5io4Rc1sr7DDqvsbXi6tmcAsOyIYzK.jpg"}')
}
const getters = {}
const mutations = {
    // 侧边栏折叠
    SET_COLLAPSE(state) {
        state.collapse = !state.collapse;
        sessionStorage.setItem('collapse', JSON.stringify(state.collapse));
    },
    SET_USERNAME(state, value) { // 设置用户名
        state.username = value;
        value && setUsername(value);
    },
    changeToolbarStatus(state, toolbarState) {
        state.toolbar = toolbarState;
        localStorage.setItem("toolbar", JSON.stringify(toolbarState));
    },
    loadCurrentUser(state, user) {
        state.currentUser = user;
        localStorage.setItem("currentUser", JSON.stringify(user));
    },
    loadWebInfo(state, webInfo) {
        webInfo.webTitle = webInfo.webTitle.split('');
        webInfo.notices = JSON.parse(webInfo.notices);
        state.webInfo = webInfo;
        localStorage.setItem("webInfo", JSON.stringify(webInfo));
    }
}
const actions = {
    // 登录
    loginAction(context, repuestData) {
        return new Promise((resolve, reject) => {
            login(repuestData).then((res) => {
                let data = res.data;
                // context.commit('SET_TOKEN', data.token);
                context.commit('SET_USERNAME', data.username);
                resolve(res);
            }).catch(error => {
                reject(error);
            })
        })
    },
    // 登出
    logoutAction({ commit }) {
        return new Promise((resolve, reject) => {
            Logout().then(response => {
                removeToken();
                removeUsername();
                // commit('SET_TOKEN', '');
                commit('SET_USERNAME', '');
                resolve(response);
            })

        })
    },
}
export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}